﻿
import socketserver
import pymysql   ##pip install PyMySQL
from datetime import datetime
import json
import configparser ##pip install configparser
import threading
import time

from win_runenvironment import *
import wmi  ## pip install wmi  ## pip install pywin32
import uuid
from hashlib import sha1, sha256


def check_environmentcode(secedstr):

    configfile = './tcpserverconfig.ini'
    config = configparser.RawConfigParser()
    config.read(configfile)

    environmentcode = config.get('tcpserver', 'environmentcode')

    if environmentcode == secedstr:
        return True
    else:
        return False


### 从数据库分解修改消息到各个控制卡的同步表记录
def db_SyncUpdateCmdToDeviceTable():

    ### 打开数据库连接
    db = pymysql.connect(host, user, password, libraryname)
    ### 使用cursor()方法获取操作游标
    cursor = db.cursor()

    try:
        # SQL 查询语句
        sql = "select * from table_updatereader ;"

        # 执行SQL语句
        cursor.execute(sql)
        db.commit()
        # 获取所有记录列表
        results = cursor.fetchall()

        for row in results:
            readername = row[1]
            readerid = row[2]
            cardid = row[3]
            departmentname = row[4]
            type = row[5]
            gatenumber = row[6]
            cardpassword = row[7]
            cardforcepass = row[8]
            validstart = row[9]
            validend = row[10]
            entrancevalidstart = row[11]
            entrancevalidend = row[12]
            leavevalidstart =  row[13]
            leavevalidend = row[14]
            # userage = row[15]
            # usergender = row[16]
            # picfilename = row[17]
            targetdeviceid = row[18]


            ###
            ### 获取门号对应的多个设备id
            ###
            # SQL 查询语句

            query_deviceid_sql = ""
            if targetdeviceid != "default":
                ### 根据指定的新增deviceid发送一次
                query_deviceid_sql = "select * from table_gate where deviceid='%s' "%(targetdeviceid)
            else:
                ### 根据门号匹配所有deviceid
                query_deviceid_sql = "select * from table_gate where gatenumber='%s' " % (gatenumber)

            query_deviceid_cursor = db.cursor()
            query_deviceid_cursor.execute(query_deviceid_sql)
            db.commit()
            # 获取所有记录列表
            query_deviceid_sql_results = query_deviceid_cursor.fetchall()

            for eachdevicerow in query_deviceid_sql_results:

                # gatenumber = eachdevicerow[0]  ### 根据查询而来的门号
                deviceid = eachdevicerow[2]

                getnow = datetime.now()
                transid = str(getnow.hour) + str(getnow.minute) + str(getnow.second) + str(getnow.microsecond)

                insert_upatetodeviceid_sql = \
                    "insert into table_updatetodevice" \
                     "(" \
                    "deviceid, readername, readerid, cardid, departmentname, type, gatenumber," \
                    "cardpassword, cardforcepass, validstart, validend, " \
                    "entrancevalidstart, entrancevalidend," \
                    "leavevalidstart, leavevalidend, age, gender, picfilename, transid, ackstatus" \
                    ")" + \
                     "VALUES(" \
                    "'%s', '%s', '%s', '%s', '%s', '%s', '%s'," \
                     % (deviceid, readername, readerid, cardid, departmentname, type, gatenumber) +\
                        "'%s', '%s', '%s', '%s'," \
                     %(cardpassword, cardforcepass, validstart, validend) + \
                     "'%s', '%s', '%s', '%s', 20, '', './', '%s', 'waitack')" \
                     % (entrancevalidstart, entrancevalidend, leavevalidstart, leavevalidend, transid)

                insert_updatetodeviceid_cursor = db.cursor()
                insert_updatetodeviceid_cursor.execute(insert_upatetodeviceid_sql)
                db.commit()


            delsql = "delete from table_updatereader " \
                     "where readerid = '%s' and cardid = '%s' "%(readerid, cardid)

            # cursor = db.cursor()
            # 执行SQL语句
            cursor.execute(delsql)
            db.commit()


    except:
        print("Error: unable to fetch data， in db_SyncUpdateCmdToDeviceTable")


    # 关闭数据库连接
    cursor.close()
    db.close()
    return 0


### 从数据库分解删除消息到各个控制卡的同步表记录
def db_SyncRemoveCmdToDeviceTable():

    ### 打开数据库连接
    db = pymysql.connect(host, user, password, libraryname)
    ### 使用cursor()方法获取操作游标
    cursor = db.cursor()

    try:
        # SQL 查询语句
        sql = "select * from table_removereader;"

        # 执行SQL语句
        cursor.execute(sql)
        db.commit()
        # 获取所有记录列表
        results = cursor.fetchall()

        for row in results:
            readername = row[1]
            readerid = row[2]
            cardid = row[3]
            departmentname = row[4]
            type = row[5]
            gatenumber = row[6]
            cardpassword = row[7]
            cardforcepass = row[8]
            validstart = row[9]
            validend = row[10]
            entrancevalidstart = row[11]
            entrancevalidend = row[12]
            leavevalidstart =  row[13]
            leavevalidend = row[14]
            # userage = row[15]
            # usergender = row[16]
            # picfilename = row[17]

            ###
            ### 获取门号对应的多个设备id
            ###
            # SQL 查询语句
            query_deviceid_sql = "select * from table_gate where gatenumber='%s'"%(gatenumber)

            query_deviceid_cursor = db.cursor()
            query_deviceid_cursor.execute(query_deviceid_sql)
            db.commit()
            # 获取所有记录列表
            query_deviceid_sql_results = query_deviceid_cursor.fetchall()

            for eachdevicerow in query_deviceid_sql_results:

                # gatenumber = eachdevicerow[0]  ### 根据查询而来的门号
                deviceid = eachdevicerow[2]

                getnow = datetime.now()
                transid = str(getnow.hour) + str(getnow.minute) + str(getnow.second) + str(getnow.microsecond)

                insert_removetodeviceid_sql = \
                    "insert into table_removetodevice" \
                     "(" \
                    "deviceid, readerid, cardid, " \
                    "transid, ackstatus" \
                    ")" + \
                     "VALUES(" \
                    "'%s', '%s', '%s'," \
                     % (deviceid, readerid, cardid) +\
                     "'%s', 'waitack')" \
                     % (transid)

                insert_removetodeviceid_cursor = db.cursor()
                insert_removetodeviceid_cursor.execute(insert_removetodeviceid_sql)
                db.commit()


            delsql = "delete from table_removereader " \
                     "where readerid = '%s' and cardid = '%s' "%(readerid, cardid)

            # 执行SQL语句
            cursor.execute(delsql)
            db.commit()

    except:
        print("Error: unable to fetch data， in db_SyncRemoveCmdToDeviceTable")


    # 关闭数据库连接

    cursor.close()
    db.close()
    return 0


### 向控制卡发同步修改消息
def db_SyncUpdateinfo(conn, deviceid):

    jsonstr_update = ""

    ### 打开数据库连接
    db = pymysql.connect(host, user, password, libraryname)
    # 使用cursor()方法获取操作游标
    cursor = db.cursor()

    ###
    ### 检索并给控制卡发送用户更新消息
    ###
    try:
        # SQL 查询语句
        sql = "select * from table_updatetodevice where deviceid='%s' limit 1;"%(deviceid)

        # 执行SQL语句
        cursor.execute(sql)
        db.commit()
        # 获取所有记录列表
        results = cursor.fetchall()
        for row in results:
            readername = row[1]
            readerid = row[2]
            cardid = row[3]
            departmentname = row[4]
            type = row[5]
            gatenumber = row[6]
            cardpassword = row[7]
            cardforcepass = row[8]
            validstart = row[9]
            validend = row[10]
            entrancevalidstart = row[11]
            entrancevalidend = row[12]
            leavevalidstart =  row[13]
            leavevalidend = row[14]
            userage = row[15]
            usergender = row[16]
            picfilename = row[17]
            transid = row[18]
            ackstatus = row[19]


            # 打印结果
            jsonstr_update = "{\"dwdevice\":\"%s\",\"trans_id\":\"%s\",\"cmd_code\":\"DW_UPDATE_USERINFO\"," \
                             "\"idcard\":\"%s\",\"userid\":\"%s\"," \
                             "\"staffsign\":\"9fc6e221e62e342d80779742a0f601e1\"," \
                             "\"departmentname\":\"%s\"," \
                             "\"name\":\"%s\"," \
                             "\"gatenumber\":\"%s\"," \
                             "\"dwpassword\":\"%s\"," \
                             "\"dwforcepass\":\"%s\"," \
                             "\"periodofvalitystart\":\"%s\"," \
                             "\"periodofvalityend\":\"%s\"," \
                             "\"entrancevalitystart\":\"%s\"," \
                             "\"entrancevalityend\":\"%s\"," \
                             "\"leavevalitystart\":\"%s\"," \
                             "\"leavevalityend\":\"%s\"," \
                             "\"staffage\":\"%s\"," \
                             "\"picfilename\":\"%s\"}"\
                             %(deviceid, transid,
                               cardid, readerid, departmentname,readername,gatenumber,
                               cardpassword,cardforcepass,validstart,validend,
                               entrancevalidstart,entrancevalidend,leavevalidstart,leavevalidend,
                               userage,picfilename
                               )

            # print("jsonstr_update:deviceid %s,transid %s,cardid %s, readerid %s"%(deviceid, transid, cardid, readerid))
            print("jsonstr_update:", jsonstr_update)

            conn.sendall(jsonstr_update.encode())

            ### 只处理第一个操作命令
            break

    except:
        print("Error: unable to fetch data， in db_SyncUpdateinfo")

    # 关闭数据库连接
    cursor.close()
    db.close()
    return jsonstr_update


### 向控制卡发同步删除消息
def db_SyncRemoveinfo(conn, deviceid):

    ### 打开数据库连接
    db = pymysql.connect(host, user, password, libraryname)

    # 使用cursor()方法获取操作游标
    cursor = db.cursor()

    jsonstr_remove = ""

    try:
        # SQL 查询语句
        sql = "select * from table_removetodevice where deviceid='%s' limit 1 ;" % (deviceid)

        # 执行SQL语句
        cursor.execute(sql)
        db.commit()
        # 获取所有记录列表
        results = cursor.fetchall()
        for row in results:
            readerid = row[1]
            cardid = row[2]
            transid = row[3]
            ackstatus = row[4]

            # 打印结果
            jsonstr_remove = "{\"dwdevice\":\"%s\",\"trans_id\":\"%s\"," \
                             "\"cmd_code\":\"DW_DELETE_USERINFO\",\"userid\":\"%s\"}"\
                             %(deviceid, transid, readerid)

            print("jsonstr_remove:", jsonstr_remove)
            conn.sendall(jsonstr_remove.encode())

            ### 只处理第一个操作命令
            break

    except:
        print("Error: unable to fetch data， in db_SyncRemoveinfo")

    # 关闭数据库连接
    cursor.close()
    db.close()
    return jsonstr_remove


def db_clearTodevicerecord(deviceid, transid, cmdresult):

    ### 打开数据库连接
    db = pymysql.connect(host, user, password, libraryname)
    # 使用cursor()方法获取操作游标
    cursor = db.cursor()

    ###
    ### 如果更新成功，则去掉向设备卡发送的更新记录
    ###
    try:

        if cmdresult == "OK":

            # SQL 查询语句
            sql1 = "delete from table_updatetodevice where deviceid = '%s' and transid = '%s';"%(deviceid, transid)
            sql2 = "delete from table_removetodevice where deviceid = '%s' and transid = '%s';" % (deviceid, transid)

            # 执行SQL语句
            cursor.execute(sql1)
            db.commit()
            cursor.execute(sql2)
            db.commit()

    except:
        print("Error: unable to delete data, db_clearTodevicerecord")

    # 关闭数据库连接
    cursor.close()
    db.close()


### 向数据库的table_gate更新该控制卡的最近联系时间
def db_UpdateGateActiveTimeInfo(deviceid):

    ### 打开数据库连接
    db = pymysql.connect(host, user, password, libraryname)
    # 使用cursor()方法获取操作游标
    cursor = db.cursor()

    try:

        # SQL语句
        getnow = datetime.now()
        strDateTime = getnow.strftime("%Y-%m-%d %H:%M:%S")
        timestamp = getnow.timestamp()

        # timestr = str(getnow.hour) + str(getnow.minute) + str(getnow.second) + str(getnow.microsecond)

        # sql = "select * from table_removetodevice where deviceid='%s';" % (deviceid)
        sql = "update table_gate set  lastcontacttime = '%s' , lastcontacttimestamp = '%s' where deviceid = '%s' " %(strDateTime, str(timestamp), deviceid)

        # 执行SQL语句
        cursor.execute(sql)
        db.commit()

    except Exception as err:
        print("Error: unable to execute sql, in db_UpdateGateActiveTimeInfo,", err)

    # 关闭数据库连接
    cursor.close()
    db.close()
    return 0


### 向数据库的table_gate更新该控制卡的accessstat
def db_UpdateGateAccessstat(deviceid):

    ### 打开数据库连接
    db = pymysql.connect(host, user, password, libraryname)
    # 使用cursor()方法获取操作游标
    cursor = db.cursor()

    try:

        # SQL语句
        sql = "update table_gate set lastaccessstat = '%s'  where deviceid = '%s' " %('openpass', deviceid)

        # 执行SQL语句
        cursor.execute(sql)
        db.commit()

    except:
        print("Error: unable to execute sql, in db_UpdateGateAccessstat")


    # print("db_UpdateGateAccessstat, to deviceid:%s, %s"%(deviceid, datetime.now()))

    # 关闭数据库连接
    cursor.close()
    db.close()
    return 0


def Check_Sync_DeviceTime(conn, device_time):

    if (len(device_time) < 1):
        return

    getnow = datetime.now()
    transid = str(getnow.hour) + str(getnow.minute) + str(getnow.second) + str(getnow.microsecond)

    devicedt = datetime.strptime(device_time, "%Y%m%d%H%M%S")
    timestampdiff = abs(getnow.timestamp() - devicedt.timestamp())
    if timestampdiff > 120:

        synctime = getnow.strftime("%Y%m%d%H%M%S")

        # 打印结果
        jsonstr_synctime = "{\"trans_id\":\"%s\",\"cmd_code\":\"DW_UPDATETIME\"," \
                             "\"time\":\"%s\"}" \
                         % (transid, synctime)

        print("jsonstr_synctime:", jsonstr_synctime)
        conn.sendall(jsonstr_synctime.encode())

    pass


class echorequestserver(socketserver.BaseRequestHandler):

    def handle(self):

        print("服务端启动...", datetime.now())

        conn = self.request
        print("获得连接：", self.client_address)

        bFoundoldconn = False
        oldclientconnectionlist = []
        for eachconn in connection_list:
            if eachconn[1][0] == self.client_address[0]:
                oldclientconnectionlist.append(eachconn)
                bFoundoldconn = True


        if bFoundoldconn:
            for eacholdconn in oldclientconnectionlist:
                connection_list.remove(eacholdconn)

        connection_list.append([conn, self.client_address])

        print("connection_list：")
        for eachconn in connection_list:
            print(eachconn[1])

        while True:

            start_time = time.time()

            ### 处理接收数据
            client_data = conn.recv(1024)
            if not client_data:
                print("无数据或客户端关闭连接", datetime.now())
                print("no data, time elapse:%f" % (time.time() - start_time))

                connection_list.remove([conn, self.client_address])
                # for eachconn in connection_list:
                #     print("connection_list after remove:", eachconn[1])

                break

            try:

                start_time = time.time()
                print("recv client data:", client_data.decode('utf-8'), datetime.now())
                json_str = client_data

                # db_SyncUpdateCmdToDeviceTable()
                # print("sync update cmd to devicetable, time elapse:%f" % (time.time() - start_time))
                # start_time = time.time()

                # db_SyncRemoveCmdToDeviceTable()
                # print("sync remove cmd to devicetable, time elapse:%f" % (time.time() - start_time))
                # start_time = time.time()

                bAckmsg = False
                if (str(json_str).__contains__("[")):
                    ### 控制卡回的应答消息多带了一对括号“[ ]”，要针对性去对
                    ### 如果控制卡在ack里还带有其它消息，例如数据请求消息，则只处理ack消息(带有[])
                    startpos = json_str.find(b'[')
                    endpos = json_str.find(b']')
                    # print("subjson_str ack:", startpos, endpos)
                    subjson_str = json_str[startpos+1:endpos]
                    # print("subjson_str ack:", subjson_str)
                    json_str = subjson_str
                    # json_str = json_str[1:-1]
                    bAckmsg = True


                # 将 JSON 对象转换为 Python 字典
                jsondata = json.loads(json_str)
                # print("device_id:", jsondata['device_id'])
                # print("device_time:", jsondata['time'])

                trans_id = ""
                cmd_result = ""
                if bAckmsg:
                    ### 处理板卡的应答消息，去掉数据库中待确认记录
                    trans_id = jsondata['trans_id']
                    cmd_result = jsondata['cmd_result']
                    cmd_code = jsondata['cmd_code']
                    deviceid = jsondata['device_id']

                    # print("trans_id:", jsondata['trans_id'])
                    # print("cmd_code:", cmd_code)
                    if 'DW_OPE' in cmd_code:
                        db_UpdateGateAccessstat(deviceid)
                        print("db_UpdateGateAccessstat, time elapse:%f" % (time.time() - start_time))
                        start_time = time.time()
                        pass

                    ### 向板卡同步用户后，收到ack则清除记录
                    # db_clearTodevicerecord(deviceid, trans_id, cmd_result)
                    # print("db_clearTodevicerecord, time elapse:%f" % (time.time() - start_time))
                    # start_time = time.time()

                else:
                    ### 板卡发来的非ack的消息才有时间,
                    ### 进行时间检查:设备时间同步检测，发现时间差过大，则向板卡同步时间
                    Check_Sync_DeviceTime(conn, jsondata['time'])
                    print("Check_Sync_DeviceTime, time elapse:%f" % (time.time() - start_time))
                    start_time = time.time()
                    pass

                ###
                ### 向板卡同步：增加、修改和删除用户的消息
                ###
                # db_SyncUpdateinfo(conn, jsondata['device_id'])
                # print("db_SyncUpdateinfo, time elapse:%f" % (time.time() - start_time))
                # start_time = time.time()

                # db_SyncRemoveinfo(conn, jsondata['device_id'])
                # print("db_SyncRemoveinfo, time elapse:%f" % (time.time() - start_time))
                # start_time = time.time()

                ###
                ### 更新数据库字段中，该deviceid对应门的最近消息时间
                ###
                db_UpdateGateActiveTimeInfo(jsondata['device_id'])
                print("db_UpdateGateActiveTimeInfo, time elapse:%f" % (time.time() - start_time))

            except Exception as err:
                print("---exception:", err)


def func_checkGatestatus():

    # print('check gates status.', datetime.now())
    # start_time = time.time()

    # ### 打开数据库连接
    # db = pymysql.connect("localhost", "root", "root2018", "db_library")
    db = pymysql.connect(host, user, password, libraryname)
    # 使用cursor()方法获取操作游标
    cursor = db.cursor()


    offgatesid = []
    ongatesid = []


    try:

        # SQL语句
        getnow = datetime.now()
        timestamp = getnow.timestamp()

        # SQL 查询语句
        sql = "select Id, lastcontacttimestamp from table_gate;"

        # 执行SQL语句
        cursor.execute(sql)
        db.commit()
        # 获取所有记录列表
        results = cursor.fetchall()
        for row in results:
            gateid = row[0]
            lastcontacttimestamp = row[1]
            if (timestamp - float(lastcontacttimestamp)) > 120:
                offgatesid.append(gateid)
            else:
                ongatesid.append(gateid)

        ### 更新门的状态
        for eachgate in offgatesid:
            # print(eachgate)
            sql = "update table_gate set status = 'off'  where Id = '%s' " % (eachgate)
            cursor.execute(sql)
            db.commit()

        for eachgate in ongatesid:
            # print(eachgate)
            sql = "update table_gate set status = 'on'  where Id = '%s' " % (eachgate)
            cursor.execute(sql)
            db.commit()

        pass

    except:
        print("Error: unable to execute sql, in func_checkGatestatus")

    finally:
        ### 关闭数据库连接
        cursor.close()
        db.close()
        pass

    # print("func_checkGatestatus, time elapse:%f" % (time.time() - start_time))

    ### 重启定时器 60秒钟检查一次
    global timer
    timer = threading.Timer(60, func_checkGatestatus)
    timer.start()


def func_checkGatesAccessStatus_Sendmsgtodevice():

    # print('CheckGatesAccessStatus_Sendmsgtodevice.', datetime.now())
    # start_time = time.time()

    devicelist = []

    ### 打开数据库连接
    db = pymysql.connect(host, user, password, libraryname)
    # 使用cursor()方法获取操作游标
    cursor = db.cursor()

    try:

        # SQL语句
        # getnow = datetime.now()
        # timestamp = getnow.timestamp()

        # SQL 查询语句
        sql = "select deviceid, ipaddr, gatenumber, lastaccessidcard from table_gate " \
              "where lastaccessstat = 'open' "

        # 执行SQL语句
        cursor.execute(sql)
        db.commit()

        # 获取所有记录列表
        results = cursor.fetchall()
        for row in results:
            deviceid = row[0]
            ipaddr = row[1]
            gatenumber = row[2]
            # lastaccessidcard = row[3]

            for eachconn in connection_list:

                try:

                    # print("in checkGatesAccessStatus, client conn address:", eachconn[1], datetime.now())

                    clientconn_addr = eachconn[1][0]
                    if clientconn_addr != ipaddr:
                        ### ip地址不符，不是期望的客户端连接
                        continue

                    conn = eachconn[0]

                    getnow = datetime.now()
                    transid = str(getnow.hour) + str(getnow.minute) + str(getnow.second) + str(getnow.microsecond)

                    jsonstr_open = "{\"trans_id\":\"%s\",\"cmd_code\":\"DW_OPENCLOSE\"," \
                                   "\"gatenum\":\"%s\"}" \
                                   % (transid, gatenumber)

                    conn.sendall(jsonstr_open.encode())
                    print("jsonstr_open sent:%s, to ip:%s, %s" % (jsonstr_open, ipaddr, datetime.now()))

                    devicelist.append(deviceid)

                except Exception as err:
                    print("--exception--, in checkGatesAccessStatus:", err)
                    break


        ### 对有连接且发送成功的device进行状态修改
        for eachdevice in devicelist:

            print("clear openstat to ", eachdevice)

            # SQL 查询语句
            sql = "update table_gate set lastaccessstat = 'opencmdwaitack' where deviceid = '%s' " % (eachdevice)

            # 执行SQL语句
            cursor.execute(sql)
            db.commit()

            pass

    except Exception as err:
        print("Error: unable to execute sql, in func_checkGatesAccessStatus_Sendmsgtodevice," ,err)

    finally:

        ### 关闭数据库连接
        cursor.close()
        db.close()
        pass

    # print("func_checkGatesAccessStatus_Sendmsgtodevice, time elapse:%f" % (time.time() - start_time))

    ### 重启定时器 ###
    global timer_checkGatesAccessStatus_Sendmsgtodevice
    timer_checkGatesAccessStatus_Sendmsgtodevice = threading.Timer(0.5, func_checkGatesAccessStatus_Sendmsgtodevice)
    timer_checkGatesAccessStatus_Sendmsgtodevice.start()


if __name__ == '__main__':

    # Check_Sync_DeviceTime("111", "20180901111551")
    # db_UpdateGateActiveTimeInfo("111")
    # db_SyncUpdateCmdToDeviceTable()
    # db_SyncRemoveCmdToDeviceTable()
    # db_SyncUpdateinfo("1")
    # db_SyncRemoveinfo("1")

    ###------End of test------###

    secstr = get_environment_code_info_pre()
    currentsecstr = get_environment_code_info()

    ## 本机环境码
    if secstr != currentsecstr:
        print("Run environment error!")
        exit(0)


    ### 全局变量定义
    global connection_list, host, user, password, libraryname

    configfile = './tcpserverconfig.ini'
    config = configparser.RawConfigParser()
    config.read(configfile)

    host = config.get('mysqldb', 'ip')
    user = config.get('mysqldb', 'user')
    password = config.get('mysqldb', 'password')
    libraryname = config.get('mysqldb', 'libraryname')


    ### 客户端连接列表
    connection_list = []

    configfile = './tcpserverconfig.ini'
    config = configparser.RawConfigParser()
    config.read(configfile)

    host = config.get('mysqldb', 'ip')
    user = config.get('mysqldb', 'user')
    password = config.get('mysqldb', 'password')
    libraryname = config.get('mysqldb', 'libraryname')


    # print("sync update cmd to devicetable...")
    # start_time = time.time()
    # db_SyncUpdateCmdToDeviceTable()
    # print("sync update cmd to devicetable, time elapse:%f" % (time.time() - start_time))
    # start_time = time.time()
    # print("sync remove cmd to devicetable...")
    # db_SyncRemoveCmdToDeviceTable()
    # print("sync remove cmd to devicetable, time elapse:%f" % (time.time() - start_time))
    # start_time = time.time()

    timer = threading.Timer(60, func_checkGatestatus)
    timer.start()

    timer2 = threading.Timer(1, func_checkGatesAccessStatus_Sendmsgtodevice)
    timer2.start()

    configfile = './tcpserverconfig.ini'
    config = configparser.RawConfigParser()
    config.read(configfile)

    ip = config.get('tcpserver', 'ip')
    port = config.get('tcpserver', 'port')

    # server = socketserver.TCPServer((ip, int(port)), echorequestserver)  # 使用处理单连接的TCPServer
    server = socketserver.ThreadingTCPServer((ip, int(port)), echorequestserver)  # 使用处理多连接的TCPServer
    server.serve_forever()

